# -*- coding: utf-8 -*-
# @Time    : 2024/9/11 下午8:57
# @Author  : liujun
# @Email   : 2592730854@qq.com
# @File    : mail.py
# @Software: PyCharm

import smtplib
import os
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from config.config import Config
from common.consts import REPORT_PATH
from common.log import Log

c=Config()
logger=Log.get_logger()

def send_email(report):
    #创建部件对象
    msg=MIMEMultipart()

    # 配置email头
    msg["Subjeet"]=c.get_email("subject")
    msg["From"]= c.get_email("user")
    msg["To*"]=c.get_email("receiver")

    #格式化euail正文，同时将报告以附件的形式发送
    with open(os.path.join(REPORT_PATH,report),"rb") as f:
        body =f.read()
        attach = MIMEBase('zip','zip', rilename=report)

        #给附件重命名，一般和源文件一样
        attach.add_header('Content-Disposition','attachment',filename=('gb2312','',report))

        attach.set_payload(body)
        encoders.encode_base64(attach)
        msg.attach(attach)

        try:
            # 连接smtp服务器,发送邮件
            smtp = smtplib.SMTP()
            smtp.connect(c.get_email("server"))
            smtp.login(c.get_email("user"), c.get_email("pwd"))
            smtp.sendmail(c.get_email("user"),c.get_email("receiver"),msg.as_string())
        except Exception as e:
            print(e)
            print("发送失败")
            logger.error("邮件发送失败,请检查邮件配置")
        else:
            print("发送成功")
            logger.info("邮件发送成功")
        finally:
            smtp.quit()

if __name__ == '__main__':
    send_email("2024-09-12.log")
